package com.bt.springboot.task.delay;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author zkx
 * @Date 2023/9/25 11:17
 */
@Getter
@Slf4j
public class DelayQueueDemo implements Delayed {

	private final String taskContent;

	private final Long triggerTime;


	public DelayQueueDemo(String taskContent, Long delayTime) {
		this.taskContent = taskContent;
		this.triggerTime = System.currentTimeMillis() + delayTime * 1000;
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(triggerTime - System.currentTimeMillis(),TimeUnit.MILLISECONDS);
	}

	@Override
	public int compareTo(Delayed o) {
		return this.triggerTime.compareTo(((DelayQueueDemo)o).triggerTime);
	}

	public static void main(String[] args) {
		DelayQueue<DelayQueueDemo> delayQueue = new DelayQueue<>();
		new Thread(() ->{
			while (true){
				try {
					DelayQueueDemo queueDemo = delayQueue.take();
					log.info("获取到延迟任务:{}", queueDemo.getTaskContent());
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}).start();
		log.info("提交延迟任务");
		delayQueue.offer(new DelayQueueDemo("延迟任务1",5L));
		delayQueue.offer(new DelayQueueDemo("延迟任务2",6L));
		delayQueue.offer(new DelayQueueDemo("延迟任务3",8L));
	}
}
